<template>
  <el-button v-if="!disabled" type="primary" @click="visible = true">{{ _title }}</el-button>
  <div class="flex flex-wrap gap-2 w-full" :class="disabled ? '' : 'mt-2'">
    <div class="h-8 text-sm flex items-center bg-gray-100 px-2 rounded-2xl" v-for="item in defaultCheckedList"
      :key="item.user_id || item.department_id">
      <el-icons class="mr-1" size="1rem" :name="props.type === 'department' ? 'Menu' : 'Avatar'" />
      <div class="flex-1">{{ item.name }}</div>
      <el-icons v-if="!disabled" class="cursor-pointer ml-1" size="1rem" name="CircleClose" @click="onDelete(index)" />
    </div>
  </div>
  <el-dialog :title="_title" v-model="visible" :width="multiple ? 600 : 400" :destroy-on-close="true" append-to-body>
    <div class="h-[50vh]">
      <Organization ref="selectRef" :isDep="type === 'department'" :defaultCheckedList="defaultCheckedList"
        :rootNode="rootNode" :multiple="multiple" @change="onSelectChange" />
    </div>
    <template #footer>
      <el-button type="primary" @click="onConfirm">确定</el-button>
      <el-button @click="visible = false">取消</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue';
import Organization from './Organization.vue';

const props = defineProps({
  // 选择类型：员工 or 部门
  type: {
    type: String,
    default: 'user',
    validator: (value) => {
      return ['user', 'department'].includes(value);
    },
  },
  placeholder: String,
  // 是否多选
  multiple: Boolean,
  disabled: Boolean,
  rootNode: Object,
});

const visible = ref(false);
const _title = computed(() => {
  return props.placeholder || (props.type === 'user' ? '选择员工' : '选择部门');
});

const modelValue = defineModel({
  type: [Object, Array],
});
const selectRef = ref(null);
const onSelectChange = () => {
  if (!props.multiple) { // 如果是单选，直接关闭弹窗
    onConfirm();
  }
};
const onConfirm = () => {
  const selected = selectRef.value.getCheckedList();
  modelValue.value = props.multiple ? selected : selected[0];
  visible.value = false;
};

const defaultCheckedList = computed(() => {
  if (props.multiple) {
    return modelValue.value || [];
  } else {
    return modelValue.value ? [modelValue.value] : [];
  }
});
const onDelete = (index) => {
  if (props.multiple) {
    modelValue.value.splice(index, 1);
  } else {
    modelValue.value = null;
  }
};
</script>